package com.chint.springboot.controller;


import com.chint.springboot.model.vo.TokenVo;
import com.chint.springboot.result.Result;
import com.chint.springboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
//@RestController
@CrossOrigin
@RequestMapping("/login")
@Controller
public class LoginController {

    private final JwtUtils jwtUtils;

    @GetMapping("/home")
    public String getHome() {

        return "home/home"; // 返回 Thymeleaf 模板名称
    }



    @PostMapping("/in")
    public Result login(@RequestBody String sfId){
        TokenVo tokenVo = new TokenVo();
        String string = jwtUtils.generateToken(sfId);
        tokenVo.setToken(string);
        Claims claimsByToken = jwtUtils.getClaimsByToken(string);
        return Result.succ(tokenVo);
    }

    @GetMapping
    public String getCurrentUser(Model model) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            String username = userDetails.getUsername();
            model.addAttribute("username", username);
        } else {
            model.addAttribute("username", "Guest");
        }

        return "login"; // 返回 Thymeleaf 模板名称
    }
}
